import os

from PIL import Image


def pic2gif0(gifpath, frames_dir, fps):
    """
        将处理完成的图片合成GIF
    :param gifpath: 生成动图地址
    :param frames_dir: 图片所在文件夹
    :param fps: 每秒图片数
    :return:None
    """
    img = Image.open(frames_dir+"/1.jpg")
    images = []
    
    order = [int(i.strip(".jpg")) for i in os.listdir(frames_dir) if i.endswith(".jpg")]
    jpglist = [f"{frames_dir}/{i}.jpg" for i in sorted(order)]  # 直接读取可能非顺序帧
    
    for i, jpg in enumerate(jpglist):
        if i != 0:
            images.append(Image.open(jpg))
            print(f"将字符画写入GIF, 进度{(i + 1)}/{len(jpglist)}！")
    
    img.save(gifpath, save_all=True, append_images=images[1:], loop=int(1000/fps))
    print(f"{gifpath} 输出完成！")

if __name__ == "__main__":
    # pic2gif0("fumo/fumo_char.gif","fumo/fumo_char_frames",10)
    pic2gif0("lady/lady_char10.gif","lady/lady_char_frames",10)
